use common_base::{async_trait::async_trait, prelude::*};
use common_core::{data::MetadataType, ServiceContext, ServicePlugin, ServicePluginBase};

use crate::{context::MDMContext, metadata::MetadataManager};

pub struct DictDataLoadLimited {
    service_plugin_base: ServicePluginBase,
}

impl Default for DictDataLoadLimited {
    fn default() -> Self {
        Self {
            service_plugin_base: Default::default(),
        }
    }
}

#[async_trait]
impl ServicePlugin for DictDataLoadLimited {
    fn get_service_plugin_base(&self) -> &ServicePluginBase {
        &self.service_plugin_base
    }

    fn get_service_plugin_base_mut(&mut self) -> &mut ServicePluginBase {
        &mut self.service_plugin_base
    }

    async fn prepare_service(&self, srv_ctx: &mut dyn ServiceContext) -> Result<()> {
        let mdm_context = MDMContext::downcast_from_mut(srv_ctx)?;

        let dct_id = mdm_context.get_value_by_param_name("DCT_ID").to_owned();
        if dct_id.is_empty() {
            return Ok(());
        }

        let mdm_data_model = mdm_context.get_response_payload_mut()?;
        mdm_data_model.dct_id = dct_id.clone();

        if mdm_context.dct_metadata.is_none() {
            let mut metadata_manager = MetadataManager::get_instance(MetadataType::Dct);
            let dct_metadata = metadata_manager
                .get_metadata(mdm_context.get_service_context_base_mut(), dct_id.as_str())
                .await?;
            // mdm_context.dct_metadata = Some()
        }

        // TODO: many thing need to do
        error!("DictDataLoadLimited has many work to do,but not done yet!!!!");

        Ok(())
    }

    async fn process_service(&self, srv_ctx: &mut dyn ServiceContext) -> Result<()> {
        // do nothing
        Ok(())
    }

    async fn finish_service(&self, srv_ctx: &mut dyn ServiceContext) -> Result<()> {
        // do nothing
        Ok(())
    }
}
